package com.erp.erp_ui.money.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.enums.ModuleTypeEnum;
import com.erp.enums.OperationStatusEnum;
import com.erp.enums.OperationTypeEnum;
import com.erp.erp_entitys.business.entity.CarryDetailProductPartsEntity;
import com.erp.erp_entitys.log.entity.DataInfoLogEntity;
import com.erp.erp_entitys.money.entity.*;
import com.erp.erp_entitys.money.req.*;
import com.erp.erp_entitys.money.rsp.*;
import com.erp.erp_entitys.warehouse.entity.*;
import com.erp.erp_entitys.warehouse.req.DictionaryInfoReq;
import com.erp.erp_entitys.warehouse.rsp.DictionaryInfoRsp;
import com.erp.erp_servers.business.ICarryDetailProductPartsService;
import com.erp.erp_servers.log.IDataInfoLogService;
import com.erp.erp_servers.money.IPaymentDetailActuallyService;
import com.erp.erp_servers.money.IPaymentDetailService;
import com.erp.erp_servers.money.IPaymentRefundService;
import com.erp.erp_servers.money.IPaymentService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_servers.warehouse.IStockService;
import com.erp.erp_servers.warehouse.ITempAnnexService;
import com.erp.erp_ui.business.vo.DataInfoLogVo;
import com.erp.erp_ui.money.enums.PaymentTypeEnum;
import com.erp.erp_ui.money.req.*;
import com.erp.erp_ui.money.vo.*;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.req.AnnexReq;
import com.erp.erp_ui.warehouse.vo.AnnexVo;
import com.erp.erp_ui.warehouse.vo.DictionaryInfoVo;
import com.erp.utils.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName : PaymentService
 * @Description : 资金管理-付款业务逻辑层
 * @Author : lst
 * @Date: 2020-12-29 20:00
 */
@Service
public class PaymentService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(PaymentService.class);


    /**
     * 付款接口
     */
    private final IPaymentService paymentService;


    /**
     * 付款明细接口
     */
    private final IPaymentDetailService paymentDetailService;

    /**
     * 付款实付表接口
     */
    private final IPaymentDetailActuallyService paymentDetailActuallyService;

    /**
     * 付款退款接口
     */
    private final IPaymentRefundService paymentRefundService;


    /**
     * 附件接口
     */
    private final IAnnexService annexService;

    /**
     * 临时附件接口
     */
    private final ITempAnnexService tempAnnexService;

    /**
     * 库存接口
     */
    private final IStockService stockService;

    /**
     * 出运明细产品配件接口
     */
    private final ICarryDetailProductPartsService carryDetailProductPartsService;

    /**
     * 操作日志信息接口
     */
    private final IDataInfoLogService dataInfoLogService;


    @Autowired
    public PaymentService(IPaymentService paymentService,
                          IPaymentDetailService paymentDetailService,
                          IPaymentDetailActuallyService paymentDetailActuallyService,
                          IPaymentRefundService paymentRefundService,
                          IAnnexService annexService,
                          ITempAnnexService tempAnnexService,
                          IStockService stockService,
                          ICarryDetailProductPartsService carryDetailProductPartsService,
                          IDataInfoLogService dataInfoLogService) {
        this.paymentService = paymentService;
        this.paymentDetailService = paymentDetailService;
        this.paymentDetailActuallyService = paymentDetailActuallyService;
        this.paymentRefundService = paymentRefundService;
        this.annexService = annexService;
        this.tempAnnexService = tempAnnexService;
        this.stockService = stockService;
        this.carryDetailProductPartsService = carryDetailProductPartsService;
        this.dataInfoLogService = dataInfoLogService;
    }

    /**
     * 分页查询
     *
     * @param req 查询参数
     * @return 分页信息
     */
    public PageInfo<PaymentPageListVo> getListByPage(PaymentPageListReq req) {
        //初始化回参对象集合
        List<PaymentPageListVo> voList = new ArrayList<>();
        if (StringUtils.isEmpty(req.getOperationCode()) && StringUtils.isEmpty(req.getDeptOperationCode())) {
            PageInfo pageInfo = new PageInfo();
            pageInfo.setList(voList);
            return pageInfo;
        }
        //去除前后空格
        if (StringUtils.isNotEmpty(req.getInfo())) {
            req.setInfo(req.getInfo().trim());
        }
        //调用接口查询结果
        List<PaymentPageListRsp> list = paymentService.getPaymentPageListInfo(req);
        PageInfo pageInfo = new PageInfo(list);
        if (CollectionUtils.isEmpty(list)) {
            pageInfo.setList(voList);
            return pageInfo;
        }
        for (PaymentPageListRsp info : list) {
            PaymentPageListVo vo = new PaymentPageListVo();
            //赋值
            BeanUtils.copyProperties(info, vo);
            //应付时间
            vo.setTime(DateUtils.format(info.getTime()));
            //创建时间
            vo.setCreateDate(DateUtils.format(info.getCreateDate()));
            //实付日期
            vo.setActualPaymentDate(DateUtils.format(info.getActualPaymentDate()));
            //状态
            vo.setStatusStr(OperationStatusEnum.getDescById(info.getStatus()));
            //付款类型(1:登记预付款 2:登记货款)
            vo.setTypeStr(PaymentTypeEnum.getDescById(info.getType()));
            //付款金额
            BigDecimal amount = new BigDecimal("0");
            if(StringUtil.isNotEmpty(info.getAmount())){
                amount = info.getAmount();
            }
            //实付金额
            BigDecimal actualPaymentAmount = new BigDecimal("0");
            if(StringUtil.isNotEmpty(info.getActualPaymentAmount())){
                actualPaymentAmount = info.getActualPaymentAmount();
            }
            //剩余付款金额 = 付款金额 - 实付金额
            vo.setLastAmount(amount.subtract(actualPaymentAmount));

            voList.add(vo);
        }

        pageInfo.setList(voList);
        return pageInfo;
    }

    /**
     * 资源管理-付款-修改标记颜色
     *
     * @param req 入参实体
     */
    public void updateMarkColor(OperationReq req) {
        if (null == req || null == req.getId()) {
            return;
        }
        PaymentEntity infoReq = new PaymentEntity();
        //设置修改主键
        infoReq.setId(req.getId());
        //设修改时间
        infoReq.setModifyTime(new Date());
        //设置标记颜色
        infoReq.setMarkColor(req.getColor());
        //更新标记颜色
        paymentService.update(infoReq);
    }


    /**
     * 获取采购信息
     *
     * @param req 查询参数
     * @return 采购信息
     */
    public PageInfo<ImportPurchaseVo> getImportPurchaseByPage(ImportPurchaseReq req) {
        List<ImportPurchaseVo> voList = new ArrayList<>();
        if(StringUtils.isEmpty(req.getPurchaseNo())){
            PageInfo pageInfo = new PageInfo();
            pageInfo.setList(voList);
            return pageInfo;
        }
        //初始化查询对象
        ImportPurchaseInfoReq selectReq = new ImportPurchaseInfoReq();
        //赋值
        BeanUtils.copyProperties(req, selectReq);
        //去除前后空格
        if (StringUtils.isNotEmpty(req.getPurchaseNo())) {
            selectReq.setPurchaseNo(req.getPurchaseNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getContractNo())) {
            selectReq.setContractNo(req.getContractNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getSupplierName())) {
            selectReq.setSupplierName(req.getSupplierName().trim());
        }
        //查询
        List<ImportPurchaseRsp> purchaseList;
        if(null != req.getType() && 1 == req.getType()){
            //导入样品采购
            purchaseList = paymentService.getImportPurchaseSampleInfo(selectReq);
        }else {
            //导入采购
            purchaseList = paymentService.getImportPurchaseInfo(selectReq);
        }

        PageInfo pageInfo = new PageInfo(purchaseList);
        if (CollectionUtils.isEmpty(purchaseList)) {
            pageInfo.setList(purchaseList);
            return pageInfo;
        }
        for (ImportPurchaseRsp purchase : purchaseList) {
            ImportPurchaseVo vo = new ImportPurchaseVo();
            BeanUtils.copyProperties(purchase, vo);
            //设置主键
            vo.setStockInfoId(purchase.getId());
            //已付款金额
            BigDecimal amountPaid = new BigDecimal("0");
            if (StringUtil.isNotEmpty(purchase.getAmountPaid())) {
                amountPaid = purchase.getAmountPaid();
            }
            //采购合同总额
            BigDecimal totalPurchaseAmount = new BigDecimal("0");
            if (StringUtil.isNotEmpty(purchase.getTotalPurchaseAmount())) {
                totalPurchaseAmount = purchase.getTotalPurchaseAmount();
            }
            //未付款金额=采购合同总额-已付款金额
            BigDecimal unpaidAmount = totalPurchaseAmount.subtract(amountPaid);
            vo.setUnpaidAmount(unpaidAmount);
            //定金金额
            BigDecimal earnestMoney = purchase.getEarnestMoney();
            //已申请合计
            BigDecimal totalApplication = new BigDecimal("0");
            if (StringUtil.isNotEmpty(purchase.getTotalApplication())) {
                totalApplication = purchase.getTotalApplication();
            }
            //设置申请合计
            vo.setTotalApplication(totalApplication);
            BigDecimal amount = earnestMoney.subtract(totalApplication);
            //设置申请金额 = 应付金额-已申请合计
            vo.setApplicationAmount(amount);
            //设置应付金额 = 定金金额-已申请合计
            vo.setAmountsPayable(amount);
            //设置已分摊金额 = 已付款金额
            vo.setAllocatedAmount(amountPaid);
            //设置未分摊金额 = 未付款金额
            vo.setUnallocatedAmount(unpaidAmount);
            //设置采购已付款金额
            vo.setPurchasePaidAmount(amountPaid);
            //设置外销已收款金额
            BigDecimal saleAmountReceived = new BigDecimal("0");
            if (StringUtil.isNotEmpty(purchase.getSaleAmountReceived())) {
                saleAmountReceived = purchase.getSaleAmountReceived();
            }
            vo.setSaleAmountReceived(saleAmountReceived);
            //设置索赔金额
            vo.setClaimAmount(new BigDecimal("0"));
            //设置发票合同总额
            vo.setTotalInvoiceAmount(new BigDecimal("0"));
            //设置发票已付款金额
            vo.setInvoicePaidAmount(new BigDecimal("0"));

            voList.add(vo);
        }
        pageInfo.setList(voList);

        return pageInfo;
    }

    /**
     * 获取出运明细信息
     *
     * @param req 查询参数
     * @return 运明细信息
     */
    public PageInfo<ImportCarryDetailVo> getImportCarryDetailByPage(ImportCarryDetailInfoReq req) {
        //查询
        List<ImportCarryDetailInfoRsp> list = paymentService.getImportCarryDetailInfo(req);
        List<ImportCarryDetailVo> voList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(list);
        if (CollectionUtils.isEmpty(list)) {
            pageInfo.setList(list);
            return pageInfo;
        }
        for (ImportCarryDetailInfoRsp info : list) {
            ImportCarryDetailVo vo = new ImportCarryDetailVo();
            BeanUtils.copyProperties(info, vo);
            //出运日期
            vo.setCarryDate(DateUtils.format(info.getCarryDate()));
            //数量
            BigDecimal productNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getProductNum())) {
                productNum = info.getProductNum();
            }
            //成本单价
            BigDecimal fcUnitPrice = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getFcUnitPrice())) {
                fcUnitPrice = info.getFcUnitPrice();
            }
            //定金比例
            BigDecimal earnestRate = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getEarnestRate())) {
                earnestRate = info.getEarnestRate();
            }
            //应付金额 = 数量*成本单价*（1-定金比例）
            BigDecimal amountsPayable = productNum.multiply(fcUnitPrice).multiply((new BigDecimal("1").subtract(earnestRate)));
            vo.setAmountsPayable(amountsPayable);

            //默认获取应付金额大于零数据
            if (amountsPayable.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }

            //发票已付款金额
            BigDecimal invoicePaidAmount = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getInvoicePaidAmount())) {
                invoicePaidAmount = info.getInvoicePaidAmount();
            }
            //未付款金额(应付总金额-发票已付款金额)
            BigDecimal unPaidAmount = amountsPayable.subtract(invoicePaidAmount);
            vo.setUnPaidAmount(unPaidAmount);

            //申请金额(默认等于应付总金额)
            vo.setApplicationAmount(amountsPayable);

            //发票合同总额 = 应付总金额
            vo.setTotalInvoiceAmount(amountsPayable);

            //设置已分摊金额
            vo.setAllocatedAmount(new BigDecimal("0"));

            //设置未分摊金额
            vo.setUnallocatedAmount(new BigDecimal("0"));

            voList.add(vo);
        }
        pageInfo.setList(voList);

        return pageInfo;
    }

    /**
     * 获取出运明细信息
     *
     * @param req 查询参数
     * @return 运明细信息
     */
    public List<ImportCarryDetailVo> getImportCarryDetail(ImportCarryDetailInfoReq req) {
        //初始化回参对象集合
        List<ImportCarryDetailVo> voList = new ArrayList<>();
        //查询条件都为空时返回空
        if (checkIsEmpty(req)) {
            return voList;
        }
        //去除前后空格
        if (StringUtils.isNotEmpty(req.getBillNo())) {
            req.setBillNo(req.getBillNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getPurchaseNo())) {
            req.setPurchaseNo(req.getPurchaseNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getSaleContractNo())) {
            req.setSaleContractNo(req.getSaleContractNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getSupplierName())) {
            req.setSupplierName(req.getSupplierName().trim());
        }
        //查询
        List<ImportCarryDetailInfoRsp> list = paymentService.getImportCarryDetailInfo(req);

        if (CollectionUtils.isEmpty(list)) {
            return voList;
        }
        for (ImportCarryDetailInfoRsp info : list) {
            ImportCarryDetailVo vo = new ImportCarryDetailVo();
            BeanUtils.copyProperties(info, vo);
            //产品id
            vo.setProductId(info.getId());
            //出运日期
            vo.setCarryDate(DateUtils.format(info.getCarryDate()));
            //数量
            BigDecimal productNum = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getProductNum())) {
                productNum = info.getProductNum();
            }
            //成本单价
            BigDecimal fcUnitPrice = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getFcUnitPrice())) {
                fcUnitPrice = info.getFcUnitPrice();
            }
            //定金比例
            BigDecimal earnestRate = new BigDecimal("0");
            if (StringUtil.isNotEmpty(info.getEarnestRate())) {
                earnestRate = info.getEarnestRate().divide(new BigDecimal("100"));
            }
            if(1 == info.getProductType()){
                //成品,需要减去相关配件成本
                CarryDetailProductPartsEntity partsReq = new CarryDetailProductPartsEntity();
                //产品明细id
                partsReq.setProductDetailId(info.getId());
                //数据有效
                partsReq.setValid(DataIsValidEnum.VALID.getId());
                List<CarryDetailProductPartsEntity> partsList = carryDetailProductPartsService.queryAll(partsReq);
                if(!CollectionUtils.isEmpty(partsList)){
                    //配件成本单价合计
                    BigDecimal sumPrice = new BigDecimal("0");
                    for(CarryDetailProductPartsEntity parts : partsList){
                        if(StringUtil.isNotEmpty(parts.getCostUnitPrice())){
                            sumPrice = sumPrice.add(parts.getCostUnitPrice());
                        }
                    }
                    //成品成本 = 成本单价 - 配件成本
                    fcUnitPrice = fcUnitPrice.subtract(sumPrice);
                }
            }
            //应付金额 = 数量*成本单价*（1-定金比例）
            BigDecimal amountsPayable = productNum.multiply(fcUnitPrice).multiply((new BigDecimal("1").subtract(earnestRate))).setScale(2,BigDecimal.ROUND_HALF_UP);
            vo.setAmountsPayable(amountsPayable);

            //默认获取应付金额大于零数据
            if (amountsPayable.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }

            //已申请合计
            BigDecimal totalApplication = new BigDecimal("0");
            if(StringUtil.isNotEmpty(info.getTotalApplication())){
                totalApplication = info.getTotalApplication();
            }
            //未付款金额(应付总金额-已申请合计)
            BigDecimal unPaidAmount = amountsPayable.subtract(totalApplication).setScale(2,BigDecimal.ROUND_HALF_UP);
            vo.setUnPaidAmount(unPaidAmount);
            //未付金额大于零
            if (unPaidAmount.compareTo(BigDecimal.ZERO) < 1) {
                continue;
            }

            //申请金额(默认等于未付金额)
            vo.setApplicationAmount(unPaidAmount);

            //发票合同总额 = 应付总金额
            vo.setTotalInvoiceAmount(amountsPayable);

            //设置已分摊金额
            vo.setAllocatedAmount(new BigDecimal("0"));

            //设置未分摊金额
            vo.setUnallocatedAmount(new BigDecimal("0"));

            voList.add(vo);
        }

        return voList;
    }

    /**
     * 校验入参是否都为空
     *
     * @param req 入参实体
     * @return true:为空 false:不为空
     */
    private boolean checkIsEmpty(ImportCarryDetailInfoReq req) {
        boolean flag = StringUtils.isEmpty(req.getBillNo())
                && StringUtils.isEmpty(req.getSaleContractNo())
                && StringUtils.isEmpty(req.getPurchaseNo())
                && StringUtils.isEmpty(req.getSalesmanCode())
                && StringUtils.isEmpty(req.getSupplierName())
                && StringUtils.isEmpty(req.getTimeStart())
                && StringUtils.isEmpty(req.getTimeEnd());
        if (flag) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取付款类型
     *
     * @return 付款类型
     */
    public List<DictionaryInfoVo> getPaymentTypeInfo(DictionaryInfoReq dictionaryInfosReq) {
        //初始化回参
        List<DictionaryInfoVo> dictionaryVos = new ArrayList<>();
        List<DictionaryInfoRsp> dictionaryInfos = stockService.getDictionaryInfo(dictionaryInfosReq);
        if (CollectionUtils.isEmpty(dictionaryInfos)) {
            return dictionaryVos;
        }
        for (DictionaryInfoRsp infoRsp : dictionaryInfos) {
            DictionaryInfoVo vo = new DictionaryInfoVo();
            BeanUtils.copyProperties(infoRsp, vo);

            dictionaryVos.add(vo);
        }

        return dictionaryVos;
    }

    /**
     * 获取银行信息
     *
     * @param code 供应商编码
     * @return 银行信息
     */
    public List<BankInfoRsp> getBankInfo(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        return paymentService.getBankInfo(code);
    }

    /**
     * 获取供应商信息
     *
     * @return 供应商信息
     */
    public List<SupplierInfoRsp> getSupplierInfo() {
        return paymentService.getSupplierInfo();
    }

    /**
     * 新增、修改
     *
     * @param req      新增、修改入参
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 新增、修改结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R add(AddPaymentReq req, String creator, String createNo) throws ParseException {
        //一：单号唯一性校验
        boolean billNoCheckFlag = (null != req.getId() && req.getBillNo().equals(req.getNewBillNo()));
        if (!billNoCheckFlag) {
            //单号做唯一校验
            boolean billNoFlag = checkRepeatBillNo(req.getBillNo());
            if (!billNoFlag) {
                return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
            }
        }

        //二：付款主表新增
        Integer id = insert(req, creator, createNo);
        if (id == null) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

        //三：明细新增
        insertDetail(req, id, creator, createNo);

        //四：添加附件信息
        boolean flag = addAnnex(req.getAnnexList(), id, creator, createNo);
        if (!flag) {
            LOGGER.info("资金管理-付款-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexList());
        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 批量处理临时附件信息，将临时附件设置为失效
     *
     * @param annexReqs
     */
    private void deleteTempAnnex(List<AnnexReq> annexReqs) {
        //没有附件
        if (CollectionUtils.isEmpty(annexReqs)) {
            return;
        }
        //存在附件
        for (AnnexReq annex : annexReqs) {
            if (null != annex.getNews()) {
                //旧附件,不用修改
                continue;
            }
            TempAnnexEntity tempAnnex = new TempAnnexEntity();
            //设置临时附件id
            tempAnnex.setId(annex.getId());
            //设置修改时间
            tempAnnex.setUpdateTime(new Date());
            //将附件设置为失效
            tempAnnex.setValid(DataIsValidEnum.INVALID.getId());
            tempAnnexService.update(tempAnnex);
        }

    }

    /**
     * 附件新增
     *
     * @param annexReqs  附件信息
     * @param id         付款id
     * @param operator   操作人
     * @param operatorNo 操作人编码
     * @return 是否新增成功(true : 成功 false : 失败)
     */
    private boolean addAnnex(List<AnnexReq> annexReqs, Integer id, String operator, String operatorNo) {
        try {
            //没有附件,将该id关联的所有附件设为无效
            if (CollectionUtils.isEmpty(annexReqs)) {
                AnnexEntity annexReq = new AnnexEntity();
                annexReq.setParentId(id);
                annexReq.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                List<AnnexEntity> annexList = annexService.queryAll(annexReq);
                if (!CollectionUtils.isEmpty(annexList)) {
                    for (AnnexEntity annex : annexList) {
                        AnnexEntity updateAnnex = new AnnexEntity();
                        updateAnnex.setId(annex.getId());
                        //将被删除的附件设为失效
                        updateAnnex.setValid(DataIsValidEnum.INVALID.getId());
                        annexService.update(updateAnnex);
                    }
                }
                return true;
            }
            //存在附件,新增附件信息
            List<AnnexEntity> list = new ArrayList<>();
            //获取旧的附件id集合
            List<Integer> oldIds = new ArrayList<>();
            for (AnnexReq annexReq : annexReqs) {
                if (null != annexReq.getNews()) {
                    //属于旧附件 只取id,不新增
                    oldIds.add(annexReq.getId());
                    continue;
                }
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                //设置关联模块父id
                annex.setParentId(id);
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(operator);
                //设置操作人编码
                annex.setOperatorNo(operatorNo);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if (oldIds.size() > 0) {
                //通过调拨id获取修改附件信息
                AnnexEntity annex = new AnnexEntity();
                annex.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                annex.setParentId(id);
                //获取上次附件信息
                List<AnnexEntity> annexList = annexService.queryAll(annex);
                if (!CollectionUtils.isEmpty(annexList)) {
                    //获取上次附件id集合
                    List<Integer> oldAnnexIds = annexList.stream().map(p -> p.getId()).collect(Collectors.toList());
                    //得到被删除的附件id
                    Collection collection = new ArrayList(oldAnnexIds);
                    collection.removeAll(oldIds);
                    if (collection.size() > 0) {
                        Iterator<Integer> it = collection.iterator();
                        while (it.hasNext()) {
                            int detailId = it.next();
                            AnnexEntity annexEntity = new AnnexEntity();
                            annexEntity.setId(detailId);
                            //将被删除的附件设为失效
                            annexEntity.setValid(DataIsValidEnum.INVALID.getId());

                            annexService.update(annexEntity);
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(list)) {
                //附件批量新增
                int res = annexService.batchInsert(list);
                if (res == list.size()) {
                    return true;
                }
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 明细新增
     *
     * @param req 新增对象
     * @param id  付款id
     */
    public void insertDetail(AddPaymentReq req, int id, String creator, String createNo) throws ParseException {
        if (!CollectionUtils.isEmpty(req.getDetailList())) {
            //获取明细id集合
            List<Integer> newIds = new ArrayList<>();
            //新增明细集合
            List<PaymentDetailEntity> addPaymentDetails = new ArrayList<>();
            for (AddPaymentDetailReq detailReq : req.getDetailList()) {
                //初始化付款明细对象
                PaymentDetailEntity paymentDetail = new PaymentDetailEntity();
                //赋值
                BeanUtils.copyProperties(detailReq, paymentDetail);
                //设置付款id
                paymentDetail.setParentId(id);
                //设置出运时间
                paymentDetail.setCarryDate(DateUtils.convertStringToDate(detailReq.getCarryDate(), DateUtils.DATE_PATTERN));
                //设置数据有效性(0:无效 1:有效)
                paymentDetail.setValid(DataIsValidEnum.VALID.getId());
                if (null == detailReq.getId()) {
                    //新增

                    //新增日志信息
                    if (req.getId() != null) {
                        //表明修改新增产品
                        DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                        //模块主表id
                        dataInfoLog.setParentId(id);
                        //模块id
                        dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                        //操作人编码
                        dataInfoLog.setOperationCode(createNo);
                        //操作人名称
                        dataInfoLog.setOperationName(creator);
                        //操作类型
                        dataInfoLog.setOperationType(OperationTypeEnum.INSERT_DATA.getId());
                        //操作时间
                        dataInfoLog.setOperationTime(new Date());
                        //操作内容
                        dataInfoLog.setOperationContent("明细信息:" + "合同编号:" + paymentDetail.getContractNo() + ",发票编号:" + paymentDetail.getInvoiceNumber());

                        dataInfoLogService.insert(dataInfoLog);
                    }

                    //创建日期
                    paymentDetail.setCreateDate(new Date());
                    addPaymentDetails.add(paymentDetail);
                } else {
                    //修改

                    //添加修改日志
                    //获取修改前对象数据
                    PaymentDetailEntity oldData = paymentDetailService.queryById(detailReq.getId());
                    BeanChangeLogUtil logUtil = new BeanChangeLogUtil();
                    String info = logUtil.contrastObj(oldData, paymentDetail);
                    if(StringUtils.isNotEmpty(info)){
                        //新增日志信息
                        DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                        //模块主表id
                        dataInfoLog.setParentId(id);
                        //模块id
                        dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                        //操作人编码
                        dataInfoLog.setOperationCode(createNo);
                        //操作人名称
                        dataInfoLog.setOperationName(creator);
                        //操作类型
                        dataInfoLog.setOperationType(OperationTypeEnum.UPDATE_DATA.getId());
                        //操作时间
                        dataInfoLog.setOperationTime(new Date());
                        //操作内容
                        dataInfoLog.setOperationContent("明细信息:" + info);

                        dataInfoLogService.insert(dataInfoLog);
                    }

                    //修改时间
                    paymentDetail.setModifyTime(new Date());
                    //获取明细id
                    newIds.add(detailReq.getId());
                    paymentDetailService.update(paymentDetail);
                }

            }

            //处理被删除的明细
            handleBeenDeletedDetail(req, id, newIds, creator, createNo);

            if (!CollectionUtils.isEmpty(addPaymentDetails)) {
                //调用接口保存调拨明细
                paymentDetailService.addList(addPaymentDetails);
            }
        }
    }

    /**
     * 处理被删除的付款明细
     *
     * @param req    付款明细
     * @param id     付款主表id
     * @param newIds 修改后未被删除的调付款细id集合
     */
    private void handleBeenDeletedDetail(AddPaymentReq req, int id, List<Integer> newIds, String creator, String createNo) {
        if (null != req.getId()) {
            //修改-找出被删除的明细

            PaymentDetailEntity detailReq = new PaymentDetailEntity();
            //设置付款id
            detailReq.setParentId(id);
            //查询有效数据
            detailReq.setValid(DataIsValidEnum.VALID.getId());
            //调用接口查询结果
            List<PaymentDetailEntity> detailList = paymentDetailService.queryAll(detailReq);
            if (!CollectionUtils.isEmpty(detailList)) {
                //获取id集合
                List<Integer> oldIds = detailList.stream().map(p -> p.getId()).collect(Collectors.toList());
                //找出被删除的id
                Collection collection = new ArrayList(oldIds);
                collection.removeAll(newIds);
                if (collection.size() > 0) {
                    //遍历删除被删除的明细
                    Iterator<Integer> ids = collection.iterator();
                    while (ids.hasNext()) {
                        int detailId = ids.next();
                        //添加日志
                        PaymentDetailEntity detailEntity = paymentDetailService.queryById(detailId);
                        //新增日志信息
                        DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                        //模块主表id
                        dataInfoLog.setParentId(detailEntity.getParentId());
                        //模块id
                        dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                        //操作人编码
                        dataInfoLog.setOperationCode(createNo);
                        //操作人名称
                        dataInfoLog.setOperationName(creator);
                        //操作类型
                        dataInfoLog.setOperationType(OperationTypeEnum.DELETE_DATA.getId());
                        //操作时间
                        dataInfoLog.setOperationTime(new Date());
                        //操作内容
                        dataInfoLog.setOperationContent("明细信息:" + "合同编号:" + detailEntity.getContractNo() + ",发票编号:" + detailEntity.getInvoiceNumber());
                        dataInfoLogService.insert(dataInfoLog);

                        PaymentDetailEntity detail = new PaymentDetailEntity();
                        detail.setId(detailId);
                        detail.setModifyTime(new Date());
                        detail.setValid(DataIsValidEnum.INVALID.getId());
                        //将删除的付款明细设为无效
                        paymentDetailService.update(detail);
                    }
                }
            }
        }
    }

    /**
     * 新增付款主表信息
     *
     * @param req      新增参数
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 付款主表id
     * @throws ParseException
     */
    private Integer insert(AddPaymentReq req, String creator, String createNo) throws ParseException {
        //初始化付款对象
        PaymentEntity payment = new PaymentEntity();
        //赋值
        BeanUtils.copyProperties(req, payment);
        //时间
        payment.setTime(DateUtils.convertStringToDate(req.getTime(), DateUtils.DATE_PATTERN));

        if (2 == req.getSaveType()) {
            //保存后进待批箱
            payment.setStatus(OperationStatusEnum.PENDING_BOX.getId());
        } else {
            //保存后进草稿箱
            payment.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        }


        //设置数据有效性(0:无效 1:有效)
        payment.setValid(DataIsValidEnum.VALID.getId());

        if (null == req.getId()) {
            //新增
            //设置创建人
            payment.setOperation(creator);
            //设置创建人编码
            payment.setOperationNo(createNo);
            //设置创建时间
            payment.setCreateDate(new Date());
            //调用接口新增调拨
            return paymentService.insert(payment) == 1 ? payment.getId() : null;
        } else {
            //修改

            //添加修改日志
            //获取修改前对象数据
            PaymentEntity oldData = paymentService.queryById(req.getId());
            BeanChangeLogUtil logUtil = new BeanChangeLogUtil();
            String info = logUtil.contrastObj(oldData, payment);
            if(StringUtils.isNotEmpty(info)) {
                //新增日志信息
                DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                //模块主表id
                dataInfoLog.setParentId(req.getId());
                //模块id
                dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                //操作人编码
                dataInfoLog.setOperationCode(createNo);
                //操作人名称
                dataInfoLog.setOperationName(creator);
                //操作类型
                dataInfoLog.setOperationType(OperationTypeEnum.UPDATE_DATA.getId());
                //操作时间
                dataInfoLog.setOperationTime(new Date());
                //操作内容
                dataInfoLog.setOperationContent("主信息:" + info);

                dataInfoLogService.insert(dataInfoLog);
            }
            //设置修改时间
            payment.setModifyTime(new Date());
            return paymentService.update(payment) == 1 ? payment.getId() : null;
        }

    }

    /**
     * 校验单号是否存在
     *
     * @param billNo 单号
     * @return true:不重复 false:重复
     */
    private boolean checkRepeatBillNo(String billNo) {
        PaymentEntity req = new PaymentEntity();
        req.setBillNo(billNo);
        req.setValid(DataIsValidEnum.VALID.getId());
        List<PaymentEntity> paymentList = paymentService.queryAll(req);
        if (CollectionUtils.isEmpty(paymentList)) {
            return true;
        }
        return false;
    }

    /**
     * 详情
     *
     * @param id id
     * @return 详情
     */
    public PaymentInfoVo detail(Integer id) {
        //初始化回参对象
        PaymentInfoVo vo = new PaymentInfoVo();
        if (null == id) {
            return vo;
        }
        //第一步：获取主表信息
        PaymentEntity offer = paymentService.queryById(id);
        if (null == offer || null == offer.getId()) {
            return vo;
        }
        //赋值
        BeanUtils.copyProperties(offer, vo);
        //应付时间
        vo.setTime(DateUtils.format(offer.getTime()));
        //付款类型(1:登记预付款 2:登记货款)
        vo.setTypeStr(PaymentTypeEnum.getDescById(offer.getType()));
        //创建时间
        vo.setCreateDate(DateUtils.format(offer.getCreateDate()));

        //第二步：获取产品明细数据
        PaymentDetailEntity detailReq = new PaymentDetailEntity();
        //主id
        detailReq.setParentId(id);
        //有效数据
        detailReq.setValid(DataIsValidEnum.VALID.getId());
        //调用接口查询报价产品明细数据
        List<PaymentDetailEntity> productList = paymentDetailService.queryAll(detailReq);
        if (!CollectionUtils.isEmpty(productList)) {
            //初始化回参对象集合
            List<PaymentDetailInfoVo> detailList = new ArrayList<>();
            for (PaymentDetailEntity detailEntity : productList) {
                //初始化回参对象
                PaymentDetailInfoVo productDetailVo = new PaymentDetailInfoVo();
                //赋值
                BeanUtils.copyProperties(detailEntity, productDetailVo);
                //出运日期
                productDetailVo.setCarryDate(DateUtils.format(detailEntity.getCarryDate()));

                detailList.add(productDetailVo);
            }
            //添加产品明细数据
            vo.setDetailList(detailList);
        }

        //第三步：获取实付数据
        PaymentDetailActuallyEntity costReq = new PaymentDetailActuallyEntity();
        //设置id
        costReq.setParentId(id);
        //获取有效数据
        costReq.setValid(DataIsValidEnum.VALID.getId());
        //查询结果
        List<PaymentDetailActuallyEntity> actuallyEntities = paymentDetailActuallyService.queryAll(costReq);
        if (!CollectionUtils.isEmpty(actuallyEntities)) {
            List<PaymentActuallyVo> costList = actuallyEntities.stream().map(p -> {
                PaymentActuallyVo costVo = new PaymentActuallyVo();
                //赋值
                BeanUtils.copyProperties(p, costVo);
                //实付日期
                costVo.setTime(DateUtils.format(p.getTime()));
                return costVo;
            }).collect(Collectors.toList());

            //添加相关信息
            vo.setActuallyList(costList);
        }

        //第四步：获取退款
        PaymentRefundEntity refundReq = new PaymentRefundEntity();
        refundReq.setParentId(id);
        refundReq.setValid(DataIsValidEnum.VALID.getId());
        List<PaymentRefundEntity> refunds = paymentRefundService.queryAll(refundReq);
        //初始化回参
        List<PaymentRefundInfoVo> refundList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(refunds)) {
            for (PaymentRefundEntity refund : refunds) {
                PaymentRefundInfoVo infoVo = new PaymentRefundInfoVo();
                BeanUtils.copyProperties(refund, infoVo);
                refundList.add(infoVo);
            }
        }
        vo.setRefundList(refundList);

        //第五步：获取对应附件信息
        getAnnexDetail(id, vo);

        //第六步：获取操作日志
        getOperatorLogInfo(id, vo);

        return vo;
    }

    /**
     * 获取操作日志
     * @param id 主表id
     * @param vo 回参对象
     */
    private void getOperatorLogInfo(Integer id, PaymentInfoVo vo) {
        //第四步：获取对应日志信息
        DataInfoLogEntity logReq = new DataInfoLogEntity();
        //主表id
        logReq.setParentId(id);
        //模块id
        logReq.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
        //查询结果
        List<DataInfoLogEntity> dataInfoLog = dataInfoLogService.queryAll(logReq);
        if (!CollectionUtils.isEmpty(dataInfoLog)) {
            List<DataInfoLogVo> logVos = new ArrayList<>();
            for (DataInfoLogEntity log : dataInfoLog) {
                DataInfoLogVo logVo = new DataInfoLogVo();
                //赋值
                BeanUtils.copyProperties(log, logVo);
                //日期处理
                logVo.setOperationTime(DateUtils.format(log.getOperationTime(), DateUtils.DATE_TIME_PATTERN));
                //操作类型
                logVo.setOperationType(OperationTypeEnum.getDescById(log.getOperationType()));

                logVos.add(logVo);
            }

            vo.setLogList(logVos);
        }
    }

    /**
     * 获取附件详情
     *
     * @param id 主键id
     * @param vo 回参实体
     */
    private void getAnnexDetail(Integer id, PaymentInfoVo vo) {
        AnnexEntity annex = new AnnexEntity();
        //设置模块id
        annex.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
        //设置父id
        annex.setParentId(id);
        //设置数据有效
        annex.setValid(DataIsValidEnum.VALID.getId());
        //调用接口查询附件信息
        List<AnnexEntity> annexList = annexService.queryAll(annex);
        if (CollectionUtils.isEmpty(annexList)) {
            return;
        }
        List<AnnexVo> annexVos = annexList.stream().map(p -> {
            AnnexVo annexVo = new AnnexVo();
            //赋值
            BeanUtils.copyProperties(p, annexVo);
            //上传时间转换
            annexVo.setUploadTime(DateUtils.format(p.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
            //设置附件为旧附件,用以区分修改时附件状态
            annexVo.setNews(0);

            return annexVo;
        }).collect(Collectors.toList());

        vo.setAnnexList(annexVos);
    }

    /**
     * 付款首页-箱体操作
     *
     * @param req
     */
    public R operation(OperationReq req) {
        if (null == req.getId() || null == req.getOperation() || StringUtils.isBlank(req.getBillNo())) {
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        PaymentEntity payment = new PaymentEntity();
        //设置修改主键
        payment.setId(req.getId());
        //修改时间
        payment.setModifyTime(new Date());

        switch (req.getOperation()) {
            case 1:
                //提交审批后,状态为待批箱
                payment.setStatus(OperationStatusEnum.PENDING_BOX.getId());
                break;
            case 2:
                //审批通过,状态设为已批箱
                payment.setStatus(OperationStatusEnum.APPROVED_BOX.getId());
                break;
            case 3:
                //审批退回
                //状态设为草稿箱
                payment.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
                break;
            case 4:
                //将状态设为完成
                payment.setStatus(OperationStatusEnum.COMPLETION_BOX.getId());
                break;
            case 5:
                //点击还原，将状态改为草稿箱
                payment.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
                break;
        }
        //调用接口修改
        paymentService.update(payment);
        return R.buildError(ResultStatusEnum.SUCCESS);
    }

    /**
     * 实付新增
     *
     * @param req      实付新增入参
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 实付新增结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R addActually(AddPaymentReq req, String creator, String createNo) throws ParseException {
        //一：实付新增
        insertActually(req, creator, createNo);

        //二：添加附件信息
        boolean flag = addAnnex(req.getAnnexList(), req.getId(), creator, createNo);
        if (!flag) {
            LOGGER.info("资金管理-付款-批量新增附件异常");
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        //删除临时附件信息
        deleteTempAnnex(req.getAnnexList());
        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 退款新增
     *
     * @param req      退款新增入参
     * @param creator  创建人
     * @param createNo 创建人编码
     * @return 退款新增结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R addRefund(List<AddPaymentReq> req, String creator, String createNo) {
        for (AddPaymentReq payment : req) {
            //退款明细
            List<AddPaymentRefundReq> refundList = payment.getRefundList();
            if (CollectionUtils.isEmpty(refundList)) {
                continue;
            }
            for (AddPaymentRefundReq refundInfo : refundList) {
                PaymentRefundEntity refund = new PaymentRefundEntity();
                //赋值
                BeanUtils.copyProperties(refundInfo, refund);
                if (null == refundInfo.getId()) {
                    //新增

                    //创建时间
                    refund.setCreateDate(new Date());
                    refund.setOperationName(creator);
                    refund.setOperationCode(createNo);
                    refund.setValid(DataIsValidEnum.VALID.getId());

                    paymentRefundService.insert(refund);
                } else {
                    //修改

                    //修改时间
                    refund.setModifyTime(new Date());

                    paymentRefundService.update(refund);
                }
            }
        }
        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 实付新增
     *
     * @param req 新增对象
     * @throws ParseException
     */
    private void insertActually(AddPaymentReq req, String creator, String createNo) throws ParseException {
        //删除实付明细
        deleteActually(req, creator, createNo);

        if (CollectionUtils.isEmpty(req.getActuallyList())) {
            return;
        }
        for (AddPaymentActuallyReq actuallyReq : req.getActuallyList()) {
            //初始化实付实体
            PaymentDetailActuallyEntity actually = new PaymentDetailActuallyEntity();
            //赋值
            BeanUtils.copyProperties(actuallyReq, actually);
            //实付日期
            actually.setTime(DateUtils.convertStringToDate(actuallyReq.getTime(), DateUtils.DATE_PATTERN));
            //数据有效
            actually.setValid(DataIsValidEnum.VALID.getId());
            if (null == actuallyReq.getId()) {
                //新增

                if (req.getId() != null) {
                    //表明修改新增产品
                    //新增日志信息
                    DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                    //模块主表id
                    dataInfoLog.setParentId(req.getId());
                    //模块id
                    dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                    //操作人编码
                    dataInfoLog.setOperationCode(createNo);
                    //操作人名称
                    dataInfoLog.setOperationName(creator);
                    //操作类型
                    dataInfoLog.setOperationType(OperationTypeEnum.INSERT_DATA.getId());
                    //操作时间
                    dataInfoLog.setOperationTime(new Date());
                    //操作内容
                    dataInfoLog.setOperationContent("实付明细信息:" + "合同编号:" + actually.getContractNo() + ",发票编号:" + actually.getInvoiceNumber());

                    dataInfoLogService.insert(dataInfoLog);
                }

                //创建时间
                actually.setCreateDate(new Date());

                paymentDetailActuallyService.insert(actually);
            } else {
                //修改

                //添加修改日志
                //获取修改前对象数据
                PaymentDetailActuallyEntity oldData = paymentDetailActuallyService.queryById(actuallyReq.getId());
                BeanChangeLogUtil logUtil = new BeanChangeLogUtil();
                String info = logUtil.contrastObj(oldData, actually);
                if(StringUtils.isNotEmpty(info)){
                    //新增日志信息
                    DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                    //模块主表id
                    dataInfoLog.setParentId(actually.getParentId());
                    //模块id
                    dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                    //操作人编码
                    dataInfoLog.setOperationCode(createNo);
                    //操作人名称
                    dataInfoLog.setOperationName(creator);
                    //操作类型
                    dataInfoLog.setOperationType(OperationTypeEnum.UPDATE_DATA.getId());
                    //操作时间
                    dataInfoLog.setOperationTime(new Date());
                    //操作内容
                    dataInfoLog.setOperationContent("实付明细信息:" + info);

                    dataInfoLogService.insert(dataInfoLog);
                }

                //修改时间
                actually.setModifyTime(new Date());

                paymentDetailActuallyService.update(actually);
            }

        }

    }

    /**
     * 删除实付明细
     * @param req 删除的条件
     */
    private void deleteActually(AddPaymentReq req, String creator, String createNo){
        //是否存在被删除实付明细
        if (CollectionUtils.isEmpty(req.getDeleteIds())) {
            return;
        } else {
            for (Integer id : req.getDeleteIds()) {
                //添加日志
                PaymentDetailActuallyEntity detailEntity = paymentDetailActuallyService.queryById(id);
                //新增日志信息
                DataInfoLogEntity dataInfoLog = new DataInfoLogEntity();
                //模块主表id
                dataInfoLog.setParentId(detailEntity.getParentId());
                //模块id
                dataInfoLog.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
                //操作人编码
                dataInfoLog.setOperationCode(createNo);
                //操作人名称
                dataInfoLog.setOperationName(creator);
                //操作类型
                dataInfoLog.setOperationType(OperationTypeEnum.DELETE_DATA.getId());
                //操作时间
                dataInfoLog.setOperationTime(new Date());
                //操作内容
                dataInfoLog.setOperationContent("实付信息:" + "合同编号:" + detailEntity.getContractNo() + ",发票编号:" + detailEntity.getInvoiceNumber());
                dataInfoLogService.insert(dataInfoLog);

                //将数据设为无效
                PaymentDetailActuallyEntity actuallyReq = new PaymentDetailActuallyEntity();
                //设置id
                actuallyReq.setId(id);
                //修改时间
                actuallyReq.setModifyTime(new Date());
                //数据设为无效
                actuallyReq.setValid(DataIsValidEnum.INVALID.getId());

                paymentDetailActuallyService.update(actuallyReq);
            }
        }
    }

    /**
     * 获取退款登记数据
     *
     * @param id 付款id
     * @return 数据
     */
    public List<PaymentInfoVo> getPaymentInfo(String id) {
        //初始化回参对象集合
        List<PaymentInfoVo> voList = new ArrayList<>();
        if (StringUtils.isBlank(id)) {
            return voList;
        }
        //存在多个id
        List<String> ids = Arrays.asList(id.split(","));
        //获取付款信息
        List<PaymentEntity> paymentList = paymentService.getRefundInfo(ids);
        if (CollectionUtils.isEmpty(paymentList)) {
            return voList;
        }
        for (PaymentEntity payment : paymentList) {
            //初始化回参对象
            PaymentInfoVo vo = new PaymentInfoVo();
            //赋值
            BeanUtils.copyProperties(payment, vo);
            //应付时间
            vo.setTime(DateUtils.format(payment.getTime()));

            //获取明细数据
            PaymentDetailEntity detailReq = new PaymentDetailEntity();
            detailReq.setParentId(payment.getId());
            detailReq.setValid(DataIsValidEnum.VALID.getId());
            //查询明细
            List<PaymentDetailEntity> detailList = paymentDetailService.queryAll(detailReq);
            if (CollectionUtils.isEmpty(detailList)) {
                continue;
            }
            //退款明细
            List<PaymentRefundInfoVo> refundInfoVos = new ArrayList<>();
            for (PaymentDetailEntity detail : detailList) {
                //初始化查询对象
                PaymentRefundEntity refundReq = new PaymentRefundEntity();
                refundReq.setParentId(payment.getId());
                refundReq.setDetailId(detail.getId());
                refundReq.setValid(DataIsValidEnum.VALID.getId());
                //获取对应退款数据
                List<PaymentRefundEntity> refundList = paymentRefundService.queryAll(refundReq);

                //初始化回参对象
                PaymentRefundInfoVo refundVo = new PaymentRefundInfoVo();
                if (CollectionUtils.isEmpty(refundList)) {
                    //新增
                    refundVo.setParentId(payment.getId());
                    refundVo.setDetailId(detail.getId());
                    refundVo.setContractNo(detail.getContractNo());
                    refundVo.setInvoiceNumber(detail.getInvoiceNumber());
                    refundVo.setPurchaseNo(detail.getPurchaseNo());
                    refundVo.setMemo("");
                    refundVo.setAmount(new BigDecimal("0"));
                } else {
                    //修改
                    BeanUtils.copyProperties(refundList.get(0), refundVo);
                }

                refundInfoVos.add(refundVo);
            }

            vo.setRefundList(refundInfoVos);

            voList.add(vo);
        }
        return voList;
    }

    /**
     * 删除
     *
     * @param req
     */
    public void delete(OperationReq req) {
        if (null == req.getId() || null == req.getStatus()) {
            return;
        }
        PaymentEntity queryReq = new PaymentEntity();
        queryReq.setId(req.getId());
        queryReq.setModifyTime(new Date());
        if (req.getStatus().equals(OperationStatusEnum.DRAFT_BOX.getId())) {
            //草稿箱删除,数位改为垃圾箱
            queryReq.setStatus(OperationStatusEnum.TRASH_CAN.getId());
            paymentService.update(queryReq);
            return;
        } else {
            //垃圾箱删除,将主数据设为无效
            queryReq.setValid(DataIsValidEnum.INVALID.getId());
            paymentService.update(queryReq);
        }
        //获取对应明细数据
        PaymentDetailEntity detailEntity = new PaymentDetailEntity();
        detailEntity.setParentId(req.getId());
        detailEntity.setValid(DataIsValidEnum.VALID.getId());

        List<PaymentDetailEntity> detailList = paymentDetailService.queryAll(detailEntity);
        if (!CollectionUtils.isEmpty(detailList)) {
            //将所有对应有效的明细数据设为无效
            for (PaymentDetailEntity detail : detailList) {
                PaymentDetailEntity detailReq = new PaymentDetailEntity();
                detailReq.setId(detail.getId());
                detailReq.setModifyTime(new Date());
                detailReq.setValid(DataIsValidEnum.INVALID.getId());

                paymentDetailService.update(detailReq);
            }
        }

        //获取实付数据
        PaymentDetailActuallyEntity costEntity = new PaymentDetailActuallyEntity();
        costEntity.setParentId(req.getId());
        costEntity.setValid(DataIsValidEnum.VALID.getId());

        List<PaymentDetailActuallyEntity> costList = paymentDetailActuallyService.queryAll(costEntity);
        if (!CollectionUtils.isEmpty(costList)) {
            //将所有对应有效的实付数据设为无效
            for (PaymentDetailActuallyEntity cost : costList) {
                PaymentDetailActuallyEntity costReq = new PaymentDetailActuallyEntity();
                costReq.setId(cost.getId());
                costReq.setModifyTime(new Date());
                costReq.setValid(DataIsValidEnum.INVALID.getId());

                paymentDetailActuallyService.update(costReq);
            }
        }


        //获取退款数据
        PaymentRefundEntity refundReq = new PaymentRefundEntity();
        refundReq.setParentId(req.getId());
        refundReq.setValid(DataIsValidEnum.VALID.getId());
        List<PaymentRefundEntity> refundEntities = paymentRefundService.queryAll(refundReq);

        if (!CollectionUtils.isEmpty(refundEntities)) {
            //将所有对应有效的退款数据设为无效
            for (PaymentRefundEntity refund : refundEntities) {
                refund.setModifyTime(new Date());
                refund.setValid(DataIsValidEnum.INVALID.getId());

                paymentRefundService.update(refund);
            }

        }

        //获取对应所有附件
        AnnexEntity annex = new AnnexEntity();
        annex.setModuleId(ModuleTypeEnum.MONEY_PAYMENT.getId());
        annex.setParentId(req.getId());
        annex.setValid(DataIsValidEnum.VALID.getId());
        List<AnnexEntity> annexList = annexService.queryAll(annex);
        if (!CollectionUtils.isEmpty(annexList)) {
            //删除所有对应的有效的附件
            for (AnnexEntity annexData : annexList) {
                annexData.setUpdateTime(new Date());
                annexData.setValid(DataIsValidEnum.INVALID.getId());

                annexService.update(annexData);
            }
        }

    }


    //*********************付款统计*************************************
    /**
     * 获取String类型不为空数据
     * @param value 目标数据
     * @return 不为空数据
     */
    private String getNotNullOfStringInfo(String value){
        if(StringUtils.isEmpty(value)){
            return "";
        }else {
            return value;
        }
    }

    /**
     * 获取BigDecimal类型不为空的数据
     * @param value 目标数据
     * @return 不为空数据
     */
    private BigDecimal getNotNullOfBigDecimalInfo(BigDecimal value){
        if(StringUtil.isNotEmpty(value)){
            return value;
        }else {
            return new BigDecimal("0");
        }
    }
    /**
     * 付款情况统计-分页
     *
     * @param req
     * @return
     */
    public PageInfo<PaymentStatistics1Rsp> PaymentStatisticsPageInfo(PaymentStatistics1Req req) {
        List<PaymentStatistics1Rsp> paymentStatistics1RspList = paymentStatistics1RspList(req);
        PageInfo<PaymentStatistics1Rsp> pageInfo = new PageInfo<>(paymentStatistics1RspList);
        return pageInfo;
    }

    /**
     * 付款情况统计-集合
     * @param req
     * @return
     */
    public List<PaymentStatistics1Rsp> paymentStatistics1RspList(PaymentStatistics1Req req){
        List<PaymentStatistics1Rsp> paymentStatistics1RspList = paymentDetailService.paymentStatistics1List(req);
        for (PaymentStatistics1Rsp p : paymentStatistics1RspList) {
            p.setPaidStr(DateUtils.format(p.getPaidDate(), DateUtils.DATE_PATTERN));
            p.setPurchaseStr(DateUtils.format(p.getPurchaseDate(), DateUtils.DATE_PATTERN));
            p.setUnApplicationAmount(p.getPurchaseTotalPrice().subtract(p.getApplicationTotal()));
            p.setUnAmount(p.getPurchaseTotalPrice().subtract(p.getTotalAmountActuallyPaid()));
            p.setCreateTimeStr(DateUtils.format(p.getCreateTime(), DateUtils.DATE_PATTERN));
            switch (p.getPurchaseType()){
                case "1":
                    p.setPurchaseType("成品");
                    break;
                case "2":
                    p.setPurchaseType("配件");
                    break;
            }
        }
        return paymentStatistics1RspList;
    }
    /**
     * 付款情况统计-导出
     * @param req
     * @return
     */
    public JSONObject getStatisticsTwoPurchaseInfoExport(PaymentStatistics1Req req){
        List<PaymentStatistics1Rsp> purchaseStatisticsTwoResList=paymentStatistics1RspList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(purchaseStatisticsTwoResList)){
            obj.put("data", data);
            return obj;
        }
        excelInfoExport(data,purchaseStatisticsTwoResList);
        obj.put("data", data);
        return obj;
    }
    public JSONArray getTitleInfo(){
        JSONArray obj=new JSONArray();
        obj.add("序号");
        obj.add("采购签约日期");
        obj.add("采购单号");
        obj.add("采购单日期");
        obj.add("采购员");
        obj.add("外销合同号");
        obj.add("业务员");
        obj.add("付款单号");
        obj.add("收款单位");
        obj.add("币种");
        obj.add("采购单总额");
        obj.add("申请金额合计");
        obj.add("未申请金额");
        obj.add("实付金额");
        obj.add("实付日期");
        obj.add("单据类型");
        return obj;
    }
    public void excelInfoExport(JSONArray data,List<PaymentStatistics1Rsp> list ){
        //采购单总额
        BigDecimal purchaseTotalPrice = new BigDecimal("0");
        //申请金额合计
        BigDecimal applicationTotal = new BigDecimal("0");
        //未申请金额
        BigDecimal unApplicationAmount = new BigDecimal("0");
        //实付金额
        BigDecimal totalAmountActuallyPaid = new BigDecimal("0");
        Integer i=0;
        for (PaymentStatistics1Rsp vo: list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseStr()));
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseNo()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateTimeStr()));
            infoList.add(getNotNullOfStringInfo(vo.getBuyerName()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesContractNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getBillNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplierName()));
            infoList.add(getNotNullOfStringInfo(vo.getCurrency()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getPurchaseTotalPrice()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getApplicationTotal()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getUnApplicationAmount()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getTotalAmountActuallyPaid()));
            infoList.add(getNotNullOfStringInfo(vo.getPaidStr()));
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseType()));
            if(StringUtil.isNotEmpty(vo.getPurchaseTotalPrice())){
                purchaseTotalPrice = purchaseTotalPrice.add(vo.getPurchaseTotalPrice());
            }
            if(StringUtil.isNotEmpty(vo.getApplicationTotal())){
                applicationTotal = applicationTotal.add(vo.getApplicationTotal());
            }
            if(StringUtil.isNotEmpty(vo.getUnApplicationAmount())){
                unApplicationAmount = unApplicationAmount.add(vo.getUnApplicationAmount());
            }
            if(StringUtil.isNotEmpty(vo.getTotalAmountActuallyPaid())){
                totalAmountActuallyPaid = totalAmountActuallyPaid.add(vo.getTotalAmountActuallyPaid());
            }
            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(purchaseTotalPrice);
        infoList.add(applicationTotal);
        infoList.add(unApplicationAmount);
        infoList.add(totalAmountActuallyPaid);
        infoList.add("");
        infoList.add("");

        data.add(infoList);
    }


    /**
     * 采购预付款统计-集合
     * @param req
     * @return
     */
    public List<PaymentStatistics1Rsp> statisticsList(PaymentStatistics1Req req){
        //调用接口统计数据
        List<PaymentStatistics1Rsp> statisticsList = paymentDetailService.getStatisticsPurchasePrepayments(req);
        if(CollectionUtils.isEmpty(statisticsList)){
            return null;
        }
        for(PaymentStatistics1Rsp info : statisticsList){
            //时间转换
            info.setPurchaseStr(DateUtils.format(info.getPurchaseDate()));
            //未付款金额 = 采购总额 - 已付款总额
            info.setUnApplicationAmount(info.getPurchaseTotalPrice().subtract(info.getApplicationTotal()));
            switch (info.getPurchaseType()){
                case "1":
                    info.setPurchaseType("成品");
                    break;
                case "2":
                    info.setPurchaseType("配件");
                    break;
                case "3":
                    info.setPurchaseType("备货");
                    break;
                case "4":
                    info.setPurchaseType("外销");
                    break;
                case "5":
                    info.setPurchaseType("样品");
                    break;
            }
        }
        return statisticsList;
    }
    /**
     * 采购预付款统计-分页
     * @param req 查询参数
     * @return 采购预付款统计
     */
    public PageInfo<PaymentStatistics1Rsp> getStatisticsPurchasePrepayments(PaymentStatistics1Req req){
        //调用接口统计数据
        List<PaymentStatistics1Rsp> statisticsList = statisticsList(req);
        //初始化回参对象集合
        List<PaymentStatistics1Rsp> voList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(statisticsList);
        if(CollectionUtils.isEmpty(statisticsList)){
            pageInfo.setList(voList);
            return pageInfo;
        }
        pageInfo.setList(statisticsList);
        return pageInfo;
    }
    /**
     * 采购预付款统计-导出
     * @param req 查询参数
     * @return
     */
    public JSONObject getStatisticsPurchasePrepaymentExport(PaymentStatistics1Req req){
        //调用接口统计数据
        List<PaymentStatistics1Rsp> statisticsList = statisticsList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleInfoPurchase();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(statisticsList)){
            obj.put("data", data);
            return obj;
        }
        excelInfoExportPurchase(data,statisticsList);
        obj.put("data", data);
        return obj;
    }
    public JSONArray getTitleInfoPurchase(){
        JSONArray obj=new JSONArray();
        obj.add("合计");
        obj.add("采购日期");
        obj.add("采购单号");
        obj.add("采购员");
        obj.add("外销合同号");
        obj.add("业务员");
        obj.add("付款单号");
        obj.add("收款单位");
        obj.add("币种");
        obj.add("采购单总额");
        obj.add("定金比例");
        obj.add("定金金额");
        obj.add("申请金额合计");
        obj.add("未申请金额");
        obj.add("单据类型");
        obj.add("实付金额");
        return obj;
    }
    public void excelInfoExportPurchase(JSONArray data,List<PaymentStatistics1Rsp> list) {
        //采购单总额
        BigDecimal purchaseTotalPrice = new BigDecimal("0");
        //定金金额
        BigDecimal earnestMoney = new BigDecimal("0");
        //申请金额合计
        BigDecimal applicationTotal = new BigDecimal("0");
        //未申请金额
        BigDecimal  unApplicationAmount= new BigDecimal("0");
        //实付金额
        BigDecimal  actuallyAmount= new BigDecimal("0");
        Integer i=0;
        for (PaymentStatistics1Rsp vo: list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseStr()));
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseNo()));
            infoList.add(getNotNullOfStringInfo(vo.getBuyerName()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesContractNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getBillNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplierName()));
            infoList.add(getNotNullOfStringInfo(vo.getCurrency()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getPurchaseTotalPrice()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getEarnestRate()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getEarnestMoney()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getApplicationTotal()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getUnApplicationAmount()));
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseType()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getActuallyAmount()));
            if(StringUtil.isNotEmpty(vo.getPurchaseTotalPrice())){
                purchaseTotalPrice = purchaseTotalPrice.add(vo.getPurchaseTotalPrice());
            }
            if(StringUtil.isNotEmpty(vo.getTotalAmountActuallyPaid())){
                earnestMoney = earnestMoney.add(vo.getEarnestMoney());
            }
            if(StringUtil.isNotEmpty(vo.getApplicationTotal())){
                applicationTotal = applicationTotal.add(vo.getApplicationTotal());
            }
            if(StringUtil.isNotEmpty(vo.getUnApplicationAmount())){
                unApplicationAmount = unApplicationAmount.add(vo.getUnApplicationAmount());
            }
            if(StringUtil.isNotEmpty(vo.getActuallyAmount())){
                actuallyAmount = actuallyAmount.add(vo.getActuallyAmount());
            }
            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(purchaseTotalPrice);
        infoList.add("");
        infoList.add(earnestMoney);
        infoList.add(applicationTotal);
        infoList.add(unApplicationAmount);
        infoList.add("");
        infoList.add(actuallyAmount);
        data.add(infoList);
    }


    /**
     * 出货金额统计-集合
     * @param req
     * @return
     */
    public List<PaymentShipmentAmountStatisticsRsp> paymentShipmentAmountList(PaymentShipmentAmountStatisticsReq req){
        List<PaymentShipmentAmountStatisticsRsp> list = paymentDetailService.paymentShipmentAmountList(req);
        for (PaymentShipmentAmountStatisticsRsp p:list){
            p.setCreateTimeStr(DateUtils.format(p.getCreateTime(),DateUtils.DATE_PATTERN));
            p.setTotalPurchases(p.getAmount().multiply(p.getProductUnitPrice()));
            p.setTotalShipments(p.getCarryProductNum().multiply(p.getProductUnitPrice()));
        }
        return list;
    }

    /**
     * 出货金额统计-分页
     *
     * @param req
     * @return
     */
    public PageInfo<PaymentShipmentAmountStatisticsRsp> paymentShipmentAmountPageInfo(PaymentShipmentAmountStatisticsReq req) {
        List<PaymentShipmentAmountStatisticsRsp> list = paymentShipmentAmountList(req);
        PageInfo<PaymentShipmentAmountStatisticsRsp> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 出货金额统计-导出
     * @param req
     * @return
     */
    public JSONObject ExportPaymentShipmentAmount(PaymentShipmentAmountStatisticsReq req){
        List<PaymentShipmentAmountStatisticsRsp> List=paymentShipmentAmountList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getAmountTitleInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(List)){
            obj.put("data", data);
            return obj;
        }
        excelInfoAmountExport(data,List);
        obj.put("data", data);
        return obj;
    }
    public JSONArray getAmountTitleInfo(){
        JSONArray obj=new JSONArray();
        obj.add("序号");
        obj.add("采购单号");
        obj.add("供应商名称");
        obj.add("采购日期");
        obj.add("业务员");
        obj.add("操作员");
        obj.add("销售合同号");
        obj.add("产品编码");
        obj.add("规格编码");
        obj.add("采购数量");
        obj.add("出运发票号");
        obj.add("业务模式");
        obj.add("出运数量");
        obj.add("产品成本单价");
        obj.add("采购总额");
        obj.add("出货总额");
        obj.add("产品类型");
        return obj;
    }
    public void excelInfoAmountExport(JSONArray data,List<PaymentShipmentAmountStatisticsRsp> list ){
        //采购总额
        BigDecimal totalPurchases = new BigDecimal("0");
        //出货总额
        BigDecimal totalShipments = new BigDecimal("0");
        Integer i=0;
        for (PaymentShipmentAmountStatisticsRsp vo: list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplierName()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateTimeStr()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getOperationName()));
            infoList.add(getNotNullOfStringInfo(vo.getSaleContractNo()));
            infoList.add(getNotNullOfStringInfo(vo.getProductCode()));
            infoList.add(getNotNullOfStringInfo(vo.getSpecificationCode()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getAmount()));
            infoList.add(getNotNullOfStringInfo(vo.getCarryInvoiceNo()));
            infoList.add(getNotNullOfStringInfo(vo.getBusinessModelName()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getCarryProductNum()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getProductUnitPrice()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getTotalPurchases()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getTotalShipments()));
            infoList.add(getNotNullOfStringInfo(vo.getpType()));
            if(StringUtil.isNotEmpty(vo.getTotalPurchases())){
                totalPurchases = totalPurchases.add(vo.getTotalPurchases());
            }
            if(StringUtil.isNotEmpty(vo.getTotalShipments())){
                totalShipments = totalShipments.add(vo.getTotalShipments());
            }
            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(totalPurchases);
        infoList.add(totalShipments);
        infoList.add("");
        data.add(infoList);
    }


    /**
     * 采购付款统计--集合
     */
    private List<purchasePaymentStatisticsRes> purchasePaymentStatisticsResList(purchasePaymentStatisticsReq req){
        List<purchasePaymentStatisticsRes> list=paymentDetailService.purchasePaymentStatisticsResList(req);
        for (purchasePaymentStatisticsRes p: list) {
            p.setSigningDateStr(DateUtils.format(p.getSigningDate(),DateUtils.DATE_PATTERN));
        }
        return list;
    }

    /**
     * 采购付款统计--分页
     */
    public PageInfo<purchasePaymentStatisticsRes> purchasePaymentStatistics(purchasePaymentStatisticsReq req){
        List<purchasePaymentStatisticsRes> list=purchasePaymentStatisticsResList(req);
        PageInfo pageInfo=new PageInfo(list);
        return pageInfo;
    }


    /**
     * 采购付款统计-导出
     * @param req
     * @return
     */
    public JSONObject purchasePaymentStatisticsExport(purchasePaymentStatisticsReq req){
        List<purchasePaymentStatisticsRes> List=purchasePaymentStatisticsResList(req);
        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getPurchasePaymentTitleInfo();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(List)){
            obj.put("data", data);
            return obj;
        }
        excelInfoPurchasePayment(data,List);
        obj.put("data", data);
        return obj;
    }
    public JSONArray getPurchasePaymentTitleInfo(){
        JSONArray obj=new JSONArray();
        obj.add("序号");
        obj.add("采购单号");
        obj.add("供应商");
        obj.add("采购签约日期");
        obj.add("销售合同号");
        obj.add("业务员");
        obj.add("操作员");
        obj.add("采购总额");
        obj.add("出货总额");
        obj.add("申请总额");
        obj.add("实付金额");
        return obj;
    }
    public void excelInfoPurchasePayment(JSONArray data,List<purchasePaymentStatisticsRes> list ){
        //采购总额
        BigDecimal purchaseTotalPrice = new BigDecimal("0");
        //出货总额
        BigDecimal totalShipments = new BigDecimal("0");
        //申请总额
        BigDecimal applicationTotal = new BigDecimal("0");
        //实付金额
        BigDecimal totalCost = new BigDecimal("0");


        Integer i=0;
        for (purchasePaymentStatisticsRes vo: list) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getPurchaseNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplierName()));
            infoList.add(getNotNullOfStringInfo(vo.getSigningDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesContractNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSalesmanName()));
            infoList.add(getNotNullOfStringInfo(vo.getOperatorName()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getPurchaseTotalPrice()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getTotalShipments()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getApplicationTotal()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getTotalCost()));


            if(StringUtil.isNotEmpty(vo.getPurchaseTotalPrice())){
                purchaseTotalPrice = purchaseTotalPrice.add(vo.getPurchaseTotalPrice());
            }
            if(StringUtil.isNotEmpty(vo.getTotalShipments())){
                totalShipments = totalShipments.add(vo.getTotalShipments());
            }
            if(StringUtil.isNotEmpty(vo.getApplicationTotal())){
                applicationTotal = applicationTotal.add(vo.getApplicationTotal());
            }
            if(StringUtil.isNotEmpty(vo.getTotalCost())){
                totalCost = totalCost.add(vo.getTotalCost());
            }
            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(purchaseTotalPrice);
        infoList.add(totalShipments);
        infoList.add(applicationTotal);
        infoList.add(totalCost);

        data.add(infoList);
    }

    /**
     * 通过采购单号获取采购样品已做付款数量
     *
     * @param purchaseNo 采购单号
     * @return 采购样品已做付款数量
     */
    public int getResourceSampleCountByPurchaseNo(String purchaseNo) {
        if (StringUtils.isEmpty(purchaseNo)) {
            return 0;
        }
        PaymentDetailEntity req = new PaymentDetailEntity();
        req.setPurchaseNo(purchaseNo);
        req.setValid(DataIsValidEnum.VALID.getId());
        List<PaymentDetailEntity> list = paymentDetailService.queryAll(req);
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }
        return list.size();
    }



}
